package com.enjoyor.soa.traffic.util.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class JSONUtil {

	private static Gson gson;

	static {
		gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
	}

	public static synchronized Gson newInstance() {
		if (gson == null)
			gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
		return gson;
	}

	public static String toJson(Object obj) {
		return gson.toJson(obj);
	}

	public static <T> T toBean(String json, Class<T> clz) {
		return (T) gson.fromJson(json, clz);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> Map<String, T> toMap(String json, Class<T> clz) {
		Map<String, JsonObject> map = (Map) gson.fromJson(json, new TypeToken() {
		}.getType());
		Map<String, T> result = new HashMap();
		for (String key : map.keySet()) {
			result.put(key, gson.fromJson((JsonElement) map.get(key), clz));
		}
		return result;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, Object> toMap(String json) {
		Map<String, Object> map = (Map) gson.fromJson(json, new TypeToken() {
		}.getType());
		return map;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> List<T> toList(String json, Class<T> clz) {
		JsonArray array = new JsonParser().parse(json).getAsJsonArray();
		List<T> list = new ArrayList();
		for (JsonElement elem : array) {
			list.add(gson.fromJson(elem, clz));
		}
		return list;
	}

}
